import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN, ORG } from '@/store/mutation-types'

import baseapi from '@/api/base'
// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: baseapi.baseUrl, // api base_url
  timeout: 60000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 10)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  // console.log('拦截请求',config);
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['token'] = token
  }
  const org = storage.get(ORG)
  config.headers['imei'] = baseapi.imei
  if (org) {
    config.headers['org'] = org
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  // const _this = this
  // 登录状态验证，更加实际情况使用
  // C010 账号验证失败
  // C011 匿名用户
  // C012 授权过期
  // C013 设备更换
  // console.log('拦截响应',response);
  if (response.data.code === 'C011' || response.data.code === 'C012' || response.data.code === 'C013') {
    localStorage.clear()
    store.dispatch('Logout').then(() => {
      setTimeout(() => {
        window.location.reload()
      }, 100)
    })
  } else {
    const token = response.headers.token
    if (token) {
      storage.set(ACCESS_TOKEN, token, 7 * 24 * 60 * 60 * 1000)
    }
  }
  return response.data
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
